package dgo;
import java.io.InputStream;
import org.json.me.JSONObject;
import java.util.Hashtable;
import java.util.Enumeration;

public class IO {
  public static JSONObject getJSONObject(Class cls, String path){
    JSONObject jo = null;
    try 
    {
      jo = new JSONObject(readTextFile(cls, path));
    } catch (org.json.me.JSONException e) {
      System.out.println("Couldn't read " + path);
    }
    
    return jo;
  } 
  
  public static Hashtable readHashFromJSON(Class cls, String path){
    Hashtable info = new Hashtable();
    try 
    {
      JSONObject o = new JSONObject(readTextFile(cls, path));
      Enumeration e = o.keys();
      while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        String value = o.getString(name);
        info.put(name, value);
      }
    } catch (org.json.me.JSONException e) {
      System.out.println("Couldn't read " + path);
    }
    
    return info;
  } 
  
  /*--------------------------------------------------------------------------
    make it easy to load new text file from HD
   -------------------------------------------------------------------------*/
  public static String readTextFile(Class cls, String path){
    InputStream is = cls.getResourceAsStream(path);
    StringBuffer sb = new StringBuffer();
    try 
    {
      int chr = 0;
      // Read until the end of the stream      
      while ((chr = is.read()) != -1)
          sb.append((char) chr);
    } catch (Exception e) {         
      System.out.println("Unable to create stream at " + path);
    }
    return sb.toString();
  }
}
